package com.pda.common.pages.outscanf;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import com.pda.common.R;
import com.pda.common.basemvp.activity.BaseActivity;
import com.pda.common.bean.BillBean;
import com.pda.common.bean.MessageWarp;
import com.pda.common.beanin.ScanfInBean;
import com.pda.common.broadcast.NetWorkChangReceiver;
import com.pda.common.database.CodeInfo;
import com.pda.common.database.DataBaseControl;
import com.pda.common.dialogs.ChooseDialog;
import com.pda.common.pages.inscanf.InScanfActivity;
import com.pda.common.pages.inscanf.InScanfAdapter;
import com.pda.common.scan.BroadcastConfig;
import com.pda.common.tools.SharedPreferencesManger;
import com.pda.common.tools.StringProcess;
import com.pda.common.tools.VoiceUtils;
import com.pda.common.utils.PDAUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OutScanfActivity extends BaseActivity<OutScanfModel, OutScanfView, OutScanfPresent> implements OutScanfView {
    private String TAG = "OutScanfActivity";
    @BindView(R.id.login_id)
    EditText loginId;
    @BindView(R.id.loginbt)
    Button loginbt;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tvright)
    TextView tvright;
    @BindView(R.id.tvbill)
    TextView tvbill;
    @BindView(R.id.tvname)
    TextView tvname;
    @BindView(R.id.tvword)
    TextView tvword;
    @BindView(R.id.sws)
    Switch sws;
    @BindView(R.id.tvs)
    TextView tvs;
    NetWorkChangReceiver netWorkChangReceiver;
    boolean flag = true;
    List<BillBean.DataBean> listdata = new ArrayList<BillBean.DataBean>();
    List<BillBean.DataBean> listdataTemp = new ArrayList<>();
    ScanfInBean scanfInBean = new ScanfInBean();
    OutScanfAdapter outScanfAdapter;
    BillBean billBean = null;
    VoiceUtils voiceUtils;

    protected BroadcastReceiver mScanfBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BroadcastConfig.CUSTOM_NAME)) {
                String code = StringProcess.codeCL(intent.getStringExtra("scannerdata"));
                CodeInfo codeInfo = new CodeInfo();
                codeInfo.setBill(billBean.getData().get(0).getBillID());
                codeInfo.setCode(code);
                codeInfo.setType(PDAUtil.OUT);
                if (StringProcess.boxcodeJudge(code) || StringProcess.casecodeJudge(code)) {
                    if (flag) {
                        if (DataBaseControl.getCodeAllStr(codeInfo) != null) {
                            showres("条码重复");
                        } else {
                            scanfInBean.setAction("UpdateCodes");
                            scanfInBean.setCode(code);
                            BillBean billBean1 = presenter.addcode(scanfInBean);
                            if (billBean1.getErrcode() == 0) {
                                uiupdate(billBean1);
                                showres("数码:" + scanfInBean.getCode() + "出库成功");
                                DataBaseControl.addCode(codeInfo);
                            } else {
                                showres(billBean1.getErrmsg());
                            }
                        }
                    } else {
                        scanfInBean.setAction("DeleteCode");
                        scanfInBean.setCode(code);
                        BillBean billBean1 = presenter.deletecode(scanfInBean);
                        if (billBean1.getErrcode() == 0) {
                            uiupdate(billBean1);
                            showres("数码:" + scanfInBean.getCode() + "删除成功");
                            DataBaseControl.deleteCode(codeInfo);
                        } else {
                            showres(billBean1.getErrmsg());
                        }
                    }
                } else {
                    showres("条码长度不符");
                }
            }
        }
    };

    @Override
    protected void initdata() {
        tvTitle.setText("出库扫描");
        tvright.setVisibility(View.VISIBLE);
        tvright.setBackgroundResource(R.drawable.rect_blue);
        tvright.setText(" 完成 ");
        sws.setChecked(true);
        sws.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    flag = isChecked;
                } else {
                    flag = isChecked;
                }
            }
        });
        billBean = (BillBean) getIntent().getSerializableExtra(PDAUtil.keyBillDeatial);
        tvbill.setText("单号:" + billBean.getData().get(0).getBillCode());
        tvname.setText("收货方:" + billBean.getData().get(0).getDesStoreName());
        listdata = billBean.getData();
        listdataTemp.clear();
        listdataTemp.addAll(listdata);
        outScanfAdapter = new OutScanfAdapter(this, listdata);
        listview.setAdapter(outScanfAdapter);

        scanfInBean.setCid(SharedPreferencesManger.getCid());
        scanfInBean.setUserID(SharedPreferencesManger.getUID());
        scanfInBean.setStoreID(SharedPreferencesManger.getStoreID());
        scanfInBean.setBillID(billBean.getData().get(0).getBillID());
        scanfInBean.setBillListID("");
        scanfInBean.setProductID("-1");
        scanfInBean.setIsVirtualTuo(0);
        scanfInBean.setBillType(PDAUtil.OUT);
        scanfInBean.setBillCode(billBean.getData().get(0).getBillCode());

        netWorkChangReceiver = new NetWorkChangReceiver(new NetWorkChangReceiver.PriorityListener() {
            @Override
            public void setText(String string) {
                tvs.setText(string);
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkChangReceiver, filter);

        initBroadcastReciever();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastConfig.CUSTOM_NAME);
        registerReceiver(mScanfBroadcastReceiver, intentFilter);
        EventBus.getDefault().register(this);
        voiceUtils = new VoiceUtils();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_out_scanf);
        ButterKnife.bind(this);
        initdata();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkChangReceiver);
        unregisterReceiver(mScanfBroadcastReceiver);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public OutScanfModel createModel() {
        return new OutScanfModelImpl(this);
    }

    @Override
    public OutScanfView createView() {
        return this;
    }

    @Override
    public OutScanfPresent createPresenter() {
        return new OutScanfPresent();
    }


    @Override
    public void uiupdate(final BillBean abBillBean) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                listdataTemp.clear();
                listdata = abBillBean.getData();
                listdataTemp.addAll(listdata);
                if (scanfInBean.getBillListID().length() > 0) {
                    listdataTemp.get(0).setCk(true);
                }
                outScanfAdapter = new OutScanfAdapter(OutScanfActivity.this, listdataTemp);
                listview.setAdapter(outScanfAdapter);
            }
        });
    }

    @Override
    public void showres(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvword.setText(str);
            }
        });
        if (str.equals(PDAUtil.billFinish)) {
            finish();
        } else if (!str.contains("成功")) {
            voiceUtils.voiceWarn(mContext);
        }
    }

    @OnClick({R.id.iv_title_left, R.id.tvright,R.id.loginbt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tvright:
                ScanfInBean scanfInBeant = new ScanfInBean();
                scanfInBeant.setAction("CommitBill");
                scanfInBeant.setCid(SharedPreferencesManger.getCid());
                scanfInBeant.setUserID(SharedPreferencesManger.getUID());
                scanfInBeant.setStoreID(SharedPreferencesManger.getStoreID());
                scanfInBeant.setBillID(billBean.getData().get(0).getBillID());
                scanfInBeant.setBillType(PDAUtil.OUT);
                presenter.fb(scanfInBeant);
                break;
            case R.id.loginbt:
                listdataTemp.clear();
                scanfInBean.setBillListID("");
                scanfInBean.setProductID("-1");
                if (loginId.getText().toString().length() == 0) {
                    listdataTemp.addAll(listdata);
                }else {
                    for (int i = 0; i <listdata.size() ; i++) {
                        if(listdata.get(i).getProductCode().contains(loginId.getText().toString())){
                            listdataTemp.add(listdata.get(i));
                        }
                    }
                }
                outScanfAdapter = new OutScanfAdapter(OutScanfActivity.this, listdataTemp);
                listview.setAdapter(outScanfAdapter);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseMessageEvent(MessageWarp messageWarp) {
        for (int i = 0; i <listdataTemp.size() ; i++) {
            listdataTemp.get(i).setCk(false);
        }
        listdataTemp.get(messageWarp.getCode()).setCk(messageWarp.isFlag());
        if(messageWarp.isFlag()){
            scanfInBean.setBillListID(listdataTemp.get(messageWarp.getCode()).getBillListID());
            scanfInBean.setProductID(listdataTemp.get(messageWarp.getCode()).getProductID());
        }else {
            scanfInBean.setBillListID("");
            scanfInBean.setProductID("-1");
        }
        outScanfAdapter.notifyDataSetChanged();
    }
}
